package stark.app.function.callrec;

import android.Manifest;
import android.graphics.Rect;
import android.os.Build;
import android.view.View;
import android.widget.CompoundButton;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.stark.callrec.lib.CallRecService;
import com.stark.callrec.lib.db.CallRecBean;
import com.stark.callrec.lib.db.CallRecDbHelper;
import com.stark.callrec.lib.util.CallRecPrefUtil;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import stark.app.R;
import stark.app.databinding.ActivityCallrecDemoBinding;
import stark.common.basic.base.BaseNoModelActivity;
import stark.common.basic.media.audio.AudioPlayerImpl;
import stark.common.basic.utils.DialogUtil;
import stark.common.basic.utils.IntentUtil;

/**
 * Author：daizhongbin on 2022/10/31
 * Email：1027154338@qq.com
 * Desc:
 */
public class CallrecDemoActivity extends BaseNoModelActivity<ActivityCallrecDemoBinding> {

    private CallRecAdapter mAdapter;

    @Override
    protected int onCreate() {
        return R.layout.activity_callrec_demo;
    }

    @Override
    protected void initView() {
        mDataBinding.btnOpenRec.setOnClickListener(v -> {
            openRec();
        });

        //switch
        mDataBinding.scRec.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                CallRecPrefUtil.saveRecSwitchOpen(isChecked);
            }
        });
        mDataBinding.scRecIncoming.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                CallRecPrefUtil.saveRecIncomingOpen(isChecked);
            }
        });
        mDataBinding.scRecOutgoing.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                CallRecPrefUtil.saveRecOutgoingOpen(isChecked);
            }
        });

        //rv
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mDataBinding.rvRecord.setLayoutManager(layoutManager);
        mDataBinding.rvRecord.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull @NotNull Rect outRect, @NonNull @NotNull View view, @NonNull @NotNull RecyclerView parent, @NonNull @NotNull RecyclerView.State state) {
                int top = SizeUtils.dp2px(10);
                outRect.set(0, top, 0, 0);
            }
        });
        CallRecAdapter recAdapter = new CallRecAdapter();
        mAdapter = recAdapter;
        recAdapter.setOnItemClickListener(this);
        recAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull @NotNull BaseQuickAdapter adapter, @NonNull @NotNull View view, int position) {
                showDelDialog(mAdapter.getItem(position));
                return true;
            }
        });
        mDataBinding.rvRecord.setAdapter(recAdapter);

    }

    @Override
    protected void initData() {
        CallRecDbHelper.getAll().observe(this, new Observer<List<CallRecBean>>() {
            @Override
            public void onChanged(List<CallRecBean> callRecBeans) {
                mAdapter.setNewInstance(callRecBeans);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPlay();
    }

    @Override
    protected void onItemClickCallback(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
        mAdapter.setSelPos(position);
        //播放。具体播放的ui界面就没有去写了
        startPlay(mAdapter.getItem(position));
    }

    private void openRec() {
        String[] permissions = new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.READ_CALL_LOG,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.READ_CONTACTS
        };
        PermissionUtils.permission(permissions)
                .callback(new PermissionUtils.SingleCallback() {
                    @Override
                    public void callback(boolean isAllGranted, @NonNull List<String> granted, @NonNull List<String> deniedForever, @NonNull List<String> denied) {
                        if (!isAllGranted) {
                            ToastUtils.showShort("未授予权限");
                        }
                        checkDrawOverlayPermission();
                    }
                })
                .request();
    }

    private void checkDrawOverlayPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PermissionUtils.requestDrawOverlays(new PermissionUtils.SimpleCallback() {
                @Override
                public void onGranted() {
                    startCallRecService();
                    if (!CallRecService.isIsServiceConnected()) {
                        showOpenAccessServiceDialog();
                    }
                }

                @Override
                public void onDenied() {
                    ToastUtils.showShort("请授予权限");
                }
            });
        } else {
            startCallRecService();
        }
    }

    private void startCallRecService() {
        CallRecService.start(this);

        //如果需要定制悬浮窗UI的话，可以调用下面这个方法，通过第二个参数来传自己定制的悬浮窗类
        //CallRecService.startWithCustomFloatView(this, null);
    }

    private void showDelDialog(CallRecBean recBean) {
        DialogUtil.asConfirm(this, "提示", "确认删除该记录?", "取消", "确定",
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                delCallRec(recBean);
                            }
                        }, null, false)
                .show();
    }

    private void showOpenAccessServiceDialog() {
        String content = getString(com.stark.common.res.R.string.open_assist_func_tip_fmt, AppUtils.getAppName());
        DialogUtil.asConfirm(this, "提示", content, "取消", "确定",
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                IntentUtil.goAccessibilitySettings(CallrecDemoActivity.this);
                            }
                        }, null, false)
                .show();
    }

    private void delCallRec(CallRecBean recBean) {
        CallRecDbHelper.delete(recBean);
        mAdapter.remove(recBean);
        FileUtils.delete(recBean.filePath);
    }

    private AudioPlayerImpl mAudioPlayer;

    private void startPlay(CallRecBean recBean) {
        if (mAudioPlayer == null) {
            mAudioPlayer = new AudioPlayerImpl();
        }
        mAudioPlayer.play(recBean.filePath);
    }

    private void stopPlay() {
        if (mAudioPlayer != null) {
            mAudioPlayer.stop();
        }
    }

}
